package com.nanjia.boot.delivery.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.delivery.converter.DeliveryAddressConverter;
import com.nanjia.boot.delivery.mapper.DeliveryAddressMapper;
import com.nanjia.boot.delivery.model.entity.DeliveryAddress;
import com.nanjia.boot.delivery.model.form.DeliveryAddressForm;
import com.nanjia.boot.delivery.model.query.DeliveryAddressQuery;
import com.nanjia.boot.delivery.model.vo.DeliveryAddressVO;
import com.nanjia.boot.delivery.service.DeliveryAddressService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 收货/收票管理服务实现类
 *
 * @author 周洋
 * @since 2025-07-03 10:49
 */
@Service
@RequiredArgsConstructor
public class DeliveryAddressServiceImpl extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress> implements DeliveryAddressService {

    private final DeliveryAddressConverter deliveryAddressConverter;

    /**
    * 获取收货/收票管理分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<DeliveryAddressVO>} 收货/收票管理分页列表
    */
    @Override
    public IPage<DeliveryAddressVO> getDeliveryAddressPage(DeliveryAddressQuery queryParams) {
        queryParams.setSubdomainCode(SecurityUtils.getSubdomainCode());
        queryParams.setSubdomainUserCode(SecurityUtils.getUserCode());
        return this.baseMapper.getDeliveryAddressPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
    }
    
    /**
     * 获取收货/收票管理表单数据
     *
     * @param id 收货/收票管理ID
     * @return 收货/收票管理表单数据
     */
    @Override
    public DeliveryAddressForm getDeliveryAddressFormData(Long id) {
        DeliveryAddress entity = this.getById(id);
        return deliveryAddressConverter.toForm(entity);
    }
    
    /**
     * 新增收货/收票管理
     *
     * @param formData 收货/收票管理表单对象
     * @param ipAddr ip
     * @return 是否新增成功
     */
    @Override
    public boolean saveDeliveryAddress(DeliveryAddressForm formData, String ipAddr) {
        formData.setSubdomainCode(SecurityUtils.getSubdomainCode());
        formData.setSubdomainUserCode(SecurityUtils.getUserCode());
        LambdaQueryWrapper<DeliveryAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(DeliveryAddress::getId);
        List<DeliveryAddress> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getDeliveryCode());
        }
        DeliveryAddress entity = deliveryAddressConverter.toEntity(formData);
        entity.setDeliveryCode(String.format("%04d", x + 1));
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        entity.setCreateTime(LocalDateTime.now());
        entity.setDeliveryStatus(StatusEnum.ENABLE.getValue());
        entity.setSubdomainCode(SecurityUtils.getSubdomainCode());
        entity.setSubdomainUserCode(SecurityUtils.getUserCode());
        return this.save(entity);
    }
    
    /**
     * 更新收货/收票管理
     *
     * @param id   收货/收票管理ID
     * @param formData 收货/收票管理表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateDeliveryAddress(Long id,DeliveryAddressForm formData) {
        DeliveryAddress entity = deliveryAddressConverter.toEntity(formData);
        entity.setId(id);
        return this.updateById(entity);
    }
    
    /**
     * 删除收货/收票管理
     *
     * @param ids 收货/收票管理ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDeliveryAddresss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的收货/收票管理数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<DeliveryAddress> list = new ArrayList<>();
        for (Long l : idList) {
            DeliveryAddress deliveryAddress = new DeliveryAddress();
            deliveryAddress.setId(l);
            deliveryAddress.setUpdateTime(LocalDateTime.now());
            deliveryAddress.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            deliveryAddress.setDeliveryStatus(StatusEnum.DELETE.getValue());
            list.add(deliveryAddress);
        }
        return this.updateBatchById(list,idList.size());
    }

    @Override
    public List<DeliveryAddressVO> getDeliveryAddresslist(DeliveryAddressQuery queryParams) {
        System.out.println(SecurityUtils.getUserCode());
        queryParams.setSubdomainUserCode(SecurityUtils.getUserCode());
        return this.baseMapper.getDeliveryAddresslist(queryParams);
    }

    @Override
    public DeliveryAddress selectById(Integer id) {
        return this.baseMapper.selectById(id);
    }
}
